package com.software.loginregister.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.software.loginregister.R;
import com.software.loginregister.api.LikeApi;
import com.software.loginregister.entity.Post;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.vo.UserUpdateDTO;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
    private List<Post> posts;
    private Context context;
    private Long currentUserId;
    private Long postId;
    private Long targetId;
    private boolean isLiked = false;

    public PostAdapter(Context context, List<Post> posts) {
        this.context = context;
        this.posts = posts;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 创建视图并返回ViewHolder
        View view = LayoutInflater.from(context).inflate(R.layout.item_post, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Post post = posts.get(position);
        postId = post.getPostId();
        UserUpdateDTO userInfo = SharedPreferencesUtil.getUserInfo(context);
        if (userInfo != null) {
            currentUserId = userInfo.getUserId();
        }
        checkLikeStatus(holder);
        // 添加日志
        Log.d("PostAdapter", "Binding post at position " + position +
                "\nTitle: " + post.getPostTitle() +
                "\nText: " + post.getPostText() +
                "\nAvatar: " + post.getAvatar() +
                "\nImage: " + post.getPostImage());
        // 设置帖子标题
        holder.tvPostTitle.setText(post.getPostTitle() != null ? post.getPostTitle() : "无标题");
        // 设置用户头像
        if (!TextUtils.isEmpty(post.getAvatar())) {
            Glide.with(context)
                    .load(post.getAvatar())
                    .placeholder(R.drawable.ic_default_avatar)
                    .error(R.drawable.ic_default_avatar)
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            Log.e("PostAdapter", "Avatar load failed for URL: " + post.getAvatar(), e);
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            Log.d("PostAdapter", "Avatar loaded successfully: " + post.getAvatar());
                            return false;
                        }
                    })
                    .circleCrop()
                    .into(holder.ivPostAvatar);
        } else {
            holder.ivPostAvatar.setImageResource(R.drawable.ic_default_avatar);
        }
        // 设置用户名
        holder.tvPostUsername.setText(post.getNickName() != null ? post.getNickName() : "");

        // 设置帖子内容
        holder.tvPostText.setText(post.getPostText() != null ? post.getPostText() : "");

        // 设置帖子图片
        if (!TextUtils.isEmpty(post.getPostImage())) {
            holder.ivPostImage.setVisibility(View.VISIBLE);
            Glide.with(context)
                    .load(post.getPostImage())
                    .placeholder(R.drawable.loading)
                    .error(R.drawable.error)
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            Log.e("PostAdapter", "Post image load failed for URL: " + post.getPostImage(), e);
                            return false;
                        }
                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            Log.d("PostAdapter", "Post image loaded successfully: " + post.getPostImage());
                            return false;
                        }
                    })
                    .centerCrop()
                    .into(holder.ivPostImage);
        } else {
            holder.ivPostImage.setVisibility(View.GONE);
        }

        // 设置点赞和评论数
//        ivLike.setOnClickListener(v -> toggleLike());
        holder.tvPostLikeCount.setText(String.valueOf(post.getLikeCount()));
        holder.btnPostLike.setOnClickListener(v -> toggleLike(holder));
        holder.tvPostCommentCount.setText(String.valueOf(post.getCommentCount()));

        // 设置创建时间
        if (post.getCreateTime() != null) {
            holder.tvPostCreateTime.setText(formatDate(post.getCreateTime()));
        } else {
            holder.tvPostCreateTime.setText("");
        }
    }

    @Override
    public int getItemCount() {
        return posts.size(); // 返回帖子列表的大小
    }

    /**
     * ViewHolder类，用于缓存视图
     */
    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivPostAvatar, ivPostImage;// 用户头像和帖子图片
        TextView tvPostTitle, tvPostUsername, tvPostText, tvPostLikeCount, tvPostCommentCount; // 帖子标题、用户名、内容、点赞数、评论数
        TextView tvPostCreateTime;
        ImageButton btnPostLike;
        /**
         * 构造函数，初始化视图
         *
         * @param itemView 视图项
         */
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvPostTitle = itemView.findViewById(R.id.tv_post_title);
            tvPostUsername = itemView.findViewById(R.id.tv_post_username);
            ivPostAvatar = itemView.findViewById(R.id.iv_post_avatar);
            tvPostText = itemView.findViewById(R.id.tv_post_text);
            ivPostImage = itemView.findViewById(R.id.iv_post_image);
            tvPostLikeCount = itemView.findViewById(R.id.tv_post_like_count);
            tvPostCommentCount = itemView.findViewById(R.id.tv_post_comment_count);
            tvPostCreateTime = itemView.findViewById(R.id.tv_post_create_time);
            btnPostLike = itemView.findViewById(R.id.iv_like);
        }
    }
    private String formatDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        return sdf.format(date);
    }

    //点赞逻辑：
    private void toggleLike(ViewHolder holder) {
        holder.btnPostLike.setEnabled(false);
        targetId = postId;
        RetrofitClient.getInstance()
                .create(LikeApi.class)
                .toggleLike(currentUserId, targetId, "post")
                .enqueue(new Callback<Result<Map<String, Object>>>() {
                    @Override
                    public void onResponse(Call<Result<Map<String, Object>>> call,
                                           Response<Result<Map<String, Object>>> response) {
                        holder.btnPostLike.setEnabled(true);

                        if (response.isSuccessful() && response.body() != null) {
                            Result<Map<String, Object>> result = response.body();
                            if (result.getCode() == 1 && result.getData() != null) {
                                isLiked = (Boolean) result.getData().get("liked");
                                int newLikeCount = ((Number) result.getData().get("likeCount")).intValue();
                                updateLikeStatus(newLikeCount,holder);

                            } else {
                            }
                        } else {
                            try {
                                String errorBody = response.errorBody().string();
                                Log.e("RecommendDetailActivityDebug", "Error body: " + errorBody);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Map<String, Object>>> call, Throwable t) {
                        holder.btnPostLike.setEnabled(true);

                        Log.e("RecommendDetailActivityDebug", "点赞操作失败", t);
                    }
                });
    }

    private void checkLikeStatus(ViewHolder holder) {
        RetrofitClient.getInstance()
                .create(LikeApi.class)
                .isLiked(postId, currentUserId, "post")
                .enqueue(new Callback<Result<Boolean>>() {
                    @Override
                    public void onResponse(Call<Result<Boolean>> call,
                                           Response<Result<Boolean>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            Result<Boolean> result = response.body();
                            if (result.getCode() == 1 && result.getData() != null) {
                                isLiked = result.getData();
                                getLikeCount(new LikeCountCallback() {
                                    @Override
                                    public void onLikeCountReceived(int count) {
                                        updateLikeStatus(count,holder);
                                    }
                                });
                            } else {

                            }
                        } else {
                            try {
                                String errorBody = response.errorBody().string();
                                Log.e("RecommendDetailActivityDebug", "错误信息: " + errorBody);

                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Boolean>> call, Throwable t) {

                        Log.e("RecommendDetailActivityDebug", "获取点赞状态失败", t);
                    }
                });
    }
    // 修改 getLikeCount 方法定义
    private void getLikeCount(LikeCountCallback callback) {
        if (postId== null || postId == 0) {
            callback.onLikeCountReceived(0);
            return;
        }

        RetrofitClient.getInstance()
                .create(LikeApi.class)
                .getLikeCount(postId, "post")
                .enqueue(new Callback<Result<Integer>>() {
                    @Override
                    public void onResponse(Call<Result<Integer>> call,
                                           Response<Result<Integer>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            Result<Integer> result = response.body();
                            if (result.getCode() == 1 && result.getData() != null) {
                                callback.onLikeCountReceived(result.getData());
                            } else {

                                callback.onLikeCountReceived(0);
                            }
                        } else {
                            try {
                                String errorBody = response.errorBody().string();
                                Log.e("RecommendDetailActivityDebug", "错误信息: " + errorBody);

                                callback.onLikeCountReceived(0);
                            } catch (IOException e) {
                                e.printStackTrace();
                                callback.onLikeCountReceived(0);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Integer>> call, Throwable t) {
                        Log.e("RecommendDetailActivityDebug", "获取点赞数量失败", t);
                        callback.onLikeCountReceived(0);
                    }
                });
    }

    // 确保接口定义存在
    public interface LikeCountCallback {
        void onLikeCountReceived(int count);
    }

    private void updateLikeStatus(int newLikeCount,ViewHolder holder) {
        holder.btnPostLike.setImageResource(isLiked ? R.drawable.ic_heart_filled : R.drawable.ic_heart_outline);
        holder.tvPostLikeCount.setText(String.valueOf(newLikeCount));

        holder.btnPostLike.animate()
                .scaleX(1.2f)
                .scaleY(1.2f)
                .setDuration(100)
                .setInterpolator(new OvershootInterpolator())
                .withEndAction(() -> {
                    holder.btnPostLike.animate()
                            .scaleX(1f)
                            .scaleY(1f)
                            .setDuration(100)
                            .start();
                })
                .start();
    }

}